package com.dayuanit.dy16.atm.boatm.task;

import com.dayuanit.dy16.atm.boatm.entity.Salary;
import com.dayuanit.dy16.atm.boatm.entity.SalaryDetail;
import com.dayuanit.dy16.atm.boatm.enums.SalaryStatus;
import com.dayuanit.dy16.atm.boatm.mapper.SalaryDetailMapper;
import com.dayuanit.dy16.atm.boatm.mapper.SalaryMapper;
import com.dayuanit.dy16.atm.boatm.service.ISalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class PayOffTask extends BaseTask {

    @Autowired
    private SalaryMapper salaryMapper;

    @Autowired
    private SalaryDetailMapper salaryDetailMapper;

    @Autowired
    private ISalaryService salaryService;

    /**
     * 线程池
     */
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,
            3,
            10L,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue(3)
    );

    @Scheduled(cron = "0/5 * * * * ?")
    @Override
    public void doTask() {
        processPayOff();
    }

    private void processPayOff() {
        System.out.println(">>>>>发工资啦...");
        List<Salary> salaries = salaryMapper.listSalary(SalaryStatus.approved.getK());
        for (Salary salary : salaries) {
            List<SalaryDetail> details = salaryDetailMapper.listBySalaryId(salary.getId());
            for (SalaryDetail detail : details) {

                //TODO 优化  通过线程池 处理加钱

                //TODO 1.创建线程池 (面试题)
                //TODO 2.向线程池提交任务
                threadPoolExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            salaryService.payOff(detail);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

            }

            int rows = salaryMapper.updateStatus(salary.getId(), salary.getStatus(), SalaryStatus.pay_off.getK());
        }
    }
}
